package filter;

import java.awt.image.BufferedImage;
import net.jini.core.transaction.*;
import projectcvip.*;
import utils.*;

/**
 *
 * @author Michał
 */
public class FilterWorker extends JSBasic
{

    public void printTask(FilterTask task)
    {
        System.out.println("Wykonawca rozwiazuje zadanie:");
        System.out.println("MaskSize: " + task.maskSize);
        System.out.println("ChannelShift: " + task.channelShift);
        System.out.println("Path: " + task.path);
        System.out.println("FormatName: " + task.formatName);
    }

    public void go()
    {
        try
        {
            System.out.println("Wykonawca zaczyna prace.");

            while (true)
            {
                FilterTask task = new FilterTask();
                task.maskSize = null;
                task.channelShift = null;
                task.path = null;
                task.formatName = null;

                System.out.println("Wykonawca pobiera zadanie...");
                Transaction transaction = TransactionFactory.create(txnManager, defaultLease).transaction;
                task = (FilterTask) space.take(task, transaction, defaultLease);
                if (task.maskSize == null && task.channelShift == null && task.path == null && task.formatName == null)
                {
                    transaction.abort();
                    System.out.println("Wykonawca konczy prace.");
                    return;
                }
                else
                {
                    transaction.commit();
                }
                printTask(task);

                //sciezka pod ktora zostanie zapisany przefiltrowany kanal
                String channelPath = task.path.substring(0, task.path.indexOf('.')) + "_channel" + task.channelShift + ".dat";

                //wczytaj obraz
                BufferedImage img = BasicOperations.readImage(task.path);

                //filtruj kanal obrazu
                int[] channel = BasicOperations.filterChannel(img, task.maskSize, task.channelShift);

                //zapisz kanal do pliku
                BasicOperations.saveChannel(channel, channelPath, task.channelShift);

                FilterResult result = new FilterResult();
                result.channelShift = task.channelShift;
                result.filePath = channelPath;
                space.write(result, null, defaultLease);
                //img = BasicOperations.medianFilter(img, 3, 4);
                //BasicOperations.writeImage(img, pathOutput, "png");
            }
        }
        catch (Exception ex)
        {
            ex.printStackTrace();
        }
    }

    public void run()
    {
        long startTime = System.currentTimeMillis();
        go();
        long endTime = System.currentTimeMillis();
        System.out.println("Czas pracy wykonawcy: " + (endTime - startTime) + " ms.");
    }
}
